#include <config.h>
#include <encoding_manager.h>
#include <string.h>
#include <stdlib.h>

static PT_EncodingOpr g_ptEncodingOprHead = NULL;

int RegisterEncodingOpr(PT_EncodingOpr ptEncodingOpr)
{
	PT_EncodingOpr ptTmp;

	if(g_ptEncodingOprHead == NULL)
	{
		g_ptEncodingOprHead = ptEncodingOpr;
		ptEncodingOpr->ptNext = NULL;
	}
	else
	{
		ptTmp = g_ptEncodingOprHead;
		while(ptTmp->ptNext)
		{
			ptTmp = ptTmp->ptNext;
		}
		ptTmp->ptNext = ptEncodingOpr;
		ptEncodingOpr->ptNext = NULL;
	}
	return 0;
}

void ShowEncodingOpr(void)
{
	PT_EncodingOpr ptTmp;
	int i = 0;
	
	ptTmp = g_ptEncodingOprHead;	
	while(ptTmp)
	{
		printf("%02d %s\n", i++, ptTmp->name);
		ptTmp = ptTmp->ptNext;
	}
}

PT_EncodingOpr SelectEncodingForFile(unsigned char *pucBufHead)
{
	PT_EncodingOpr ptTmp;
	
	ptTmp = g_ptEncodingOprHead;
	while(ptTmp)
	{
		if(ptTmp->IsSupport(pucBufHead))
			return ptTmp;
		else
			ptTmp = ptTmp->ptNext;
	}
	return NULL;
}

int AddFontOprForEncoding(PT_EncodingOpr ptEncodingOpr, PT_FontOpr ptFontOpr)
{
	PT_FontOpr ptFontOprCpy;
	
	if(!ptEncodingOpr || !ptFontOpr)
	{
		return -1;
	}
	else
	{
		ptFontOprCpy = malloc(sizeof(T_FontOpr));
		if(!ptFontOprCpy)
		{
			return -1;
		}
		else
		{
			memcpy(ptFontOprCpy, ptFontOpr, sizeof(T_FontOpr));
			ptFontOprCpy->ptNext = ptEncodingOpr->ptFontOprSupportedHead;
			ptEncodingOpr->ptFontOprSupportedHead = ptFontOprCpy;
			return 0;
		}
	}
//	return 0;
}

int DelFontOprFrmEncoding(PT_EncodingOpr ptEncodingOpr, PT_FontOpr ptFontOpr)
{
	PT_FontOpr ptTmp;
	PT_FontOpr ptPre;
	if(!ptEncodingOpr || !ptFontOpr)
	{
		return -1;
	}
	else
	{
		ptTmp = ptEncodingOpr->ptFontOprSupportedHead;
		if(strcmp(ptTmp->name, ptFontOpr->name) == 0)
		{
			ptEncodingOpr->ptFontOprSupportedHead = ptTmp->ptNext;
			free(ptTmp);
			return 0;
		}

		ptPre = ptEncodingOpr->ptFontOprSupportedHead;
		ptTmp = ptPre->ptNext;
		while(ptTmp)
		{
			if(strcmp(ptTmp->name, ptFontOpr->name) == 0)
			{
				ptPre->ptNext = ptTmp->ptNext;
				free(ptTmp);
				return 0;
			}
			else
			{
				ptPre = ptTmp;
				ptTmp = ptTmp->ptNext;
			}
		}
		return -1;
	}
}

int EncodingInit(void)
{
	int iError;

	iError = AsciiEncodingRegister();
	if(iError)
	{
		DEG_PRINTF("Utf16leEncodingRegister error\n");
		return -1;
	}
	
	iError = Utf16beEncodingRegister();
	if(iError)
	{
		DEG_PRINTF("Utf16beEncodingRegister error\n");
		return -1;
	}
	
	iError = Utf16leEncodingRegister();
	if(iError)
	{
		DEG_PRINTF("Utf16leEncodingRegister error\n");
		return -1;
	}

	
	iError = Utf8EncodingRegister();
	if(iError)
	{
		DEG_PRINTF("Utf16leEncodingRegister error\n");
		return -1;
	}

	return 0;
}

